package avicit.bdp.dcs.semistructure.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.service.service.FileOperateCommonService;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.common.utils.CheckParaUtils;
import avicit.bdp.common.utils.database.ColumnInfo;
import avicit.bdp.common.utils.enums.FileType;
import avicit.bdp.core.constant.Constants;
import avicit.bdp.core.poi.enums.ExcelTypeEnum;
import avicit.bdp.core.poi.util.csv.ExcelToCsvUtil;
import avicit.bdp.core.util.json.JSONUtils;
import avicit.bdp.dcs.semistructure.dao.TemplateDao;
import avicit.bdp.dcs.semistructure.dto.CatalogTemplateDTO;
import avicit.bdp.dcs.semistructure.dto.ColumnRuleDto;
import avicit.bdp.dcs.semistructure.dto.TemplateDTO;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.rest.msg.QueryRespBean;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @创建时间： 2020-06-24 14:55
 * @类说明：模板管理实现类
 * @修改记录：
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TemplateService extends BaseService<TemplateDao, TemplateDTO> {

    private static final Logger logger = LoggerFactory.getLogger(TemplateService.class);

    private static final String TRANSFER_VERTICAL = "\\|";
    private static final int UNABLE = 0;
    private static final String TEMPLATE_SEPARATOR_PATTERN = "^[, |_-]${1}";
    private static final String[] fileSeparatorArray = {",", " ", "|", "_", "-"};
    private static final String TEXT = "TEXT";
    /**
     * 文件大小，单位：M
     */
    private static final int FILE_SIZE = 100 * 1024;
    /**
     * 文件长度。单位：字符
     */
    private static final int FILE_NAME_LENGTH = 30;

    /**
     * 排序，按修改时间倒序：1，按修改时间升序：2，按job名称升序：3，按job名称倒序：4
     */
    private static final int TIME_DESC = 1;
    private static final int TIME_ASC = 2;
    private static final int NAME_ASC = 3;
    private static final int NAME_DESC = 4;

    /**
     * 排序字段
     */
    private static final String ORDER_FIELD_LAST_UPDATE_DATE = "last_update_date";
    private static final String ORDER_FIELD_TEMPLATE_NAME = "template_name";

    /**
     * 排序类型
     */
    private static final String ORDER_TYPE_DESC = "desc";
    private static final String ORDER_TYPE_ASC = "asc";

    @Value("${hdfs.templateFilePath}")
    private String templateFilePath;
    @Value("${file.type.template}")
    private String templateType;
    @Value("${file.templateColumnRule}")
    private String templateColumnRule;

    @Autowired
    private TemplateDao templateDao;

    @Autowired
    private DcsFileService fileService;
    @Autowired
    private CatalogTemplateService catalogTemplateService;

    @Autowired
    private FileOperateCommonService fileOperateCommonService;

    public List<ColumnInfo> getTemplateColumnInfo(String templateId) throws Exception {
        TemplateDTO templateDTO = templateDao.selectByPrimaryKey(templateId);
        if (templateDTO == null) {
            throw new BusinessException(String.format("没有查到数据，请确保templateId：%s的模板是否存在", templateId));
        }
        if (StringUtils.isEmpty(templateDTO.getColumnRule())) {
            throw new BusinessException(String.format("templateId：%s对应的模板没有列规则数据", templateId));
        }

        return JSONUtils.toList(templateDTO.getColumnRule(), ColumnInfo.class);
    }

    public List<String> upload(TemplateDTO templateDTO) throws Exception {
        // 参数校验
        String suffix = checkParams(templateDTO);
        MultipartFile file = templateDTO.getFile();

        // 判断模板记录列表中是否有此模板
        TemplateDTO templateDtoQuery = new TemplateDTO();
        templateDtoQuery.setTemplateName(file.getOriginalFilename());
        TemplateDTO templateDTOQuery = this.selectOne(templateDtoQuery);
        if (templateDTOQuery != null) {
            throw new BusinessException(String.format("已经存在此模板，请重新上传：%s", file.getOriginalFilename()));
        }

        InputStream inputStream = file.getInputStream();
        String line = "";

        // excel类型就转成csv
        if (ExcelTypeEnum.XLS.getValue().equalsIgnoreCase(suffix) || ExcelTypeEnum.XLSX.getValue().equalsIgnoreCase(suffix)) {
            line = ExcelToCsvUtil.getHeader(inputStream, suffix);
        } else {
            // 解析模板文件返回列信息
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            line = bufferedReader.readLine();

            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

        logger.info("模板信息为：{},分隔符为：{}", line, templateDTO.getFileSeparator());

        String[] fields;
        if (Constants.VERTICAL.equals(templateDTO.getFileSeparator())) {
            // |分隔有问题，需要转义一下
            fields = line.split(TRANSFER_VERTICAL);
        } else {
            fields = line.split(templateDTO.getFileSeparator());
        }

        for (String field : fields) {
            // 对模板列字段进行校验
            if (!isValid(templateColumnRule, field)) {
                throw new BusinessException(String.format("模板格式错误，模板列只允许数字，字母大小写，下划线，横杠，并且长度限制100：%s",
                        file.getOriginalFilename()));
            }
        }

        // 上传模板文件
        fileService.uploadTemplate(file, templateFilePath);
        logger.info("上传模板文件成功:{}", file.getOriginalFilename());

        return Arrays.asList(fields);
    }

    /**
     * 根据文件自动生成模板（判断模板不存在，则新建模板）
     * @param inputStream inputStream
     * @param fileName fileName
     * @return
     * @throws Exception e
     */
    public String saveTemplate(String filePath, InputStream inputStream, String fileName) throws Exception {
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String line = "";

        // excel类型就转成csv
        if (ExcelTypeEnum.XLS.getValue().equalsIgnoreCase(suffix) || ExcelTypeEnum.XLSX.getValue().equalsIgnoreCase(suffix)) {
            line = ExcelToCsvUtil.getHeader(inputStream, suffix);
        } else {
            // 解析模板文件返回列信息
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            line = bufferedReader.readLine();

            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

        String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        String templateName = fileName.substring(0, fileName.lastIndexOf(".")) + "-template." + extensionName;

        int fileType = 2;
        FileType[] fileTypeArr = FileType.values();
        for(FileType fileTypeEnum : fileTypeArr){
            if(fileTypeEnum.getSuffix().equalsIgnoreCase(extensionName)){
                fileType = fileTypeEnum.getCode();
            }
        }
        String fileSeparator = Constants.COMMA;
        for(String separator : fileSeparatorArray){
            if(line.contains(separator)){
                fileSeparator = separator;
                break;
            }
        }

        logger.info("模板信息为：{},分隔符为：{}", line, fileSeparator);

        String[] fields = null;
        if (Constants.VERTICAL.equals(fileSeparator)) {
            // |分隔有问题，需要转义一下
            fields = line.split(TRANSFER_VERTICAL);
        } else {
            fields = line.split(fileSeparator);
        }

        for (String field : fields) {
            // 对模板列字段进行校验
            if (!isValid(templateColumnRule, field)) {
                throw new BusinessException(String.format("模板格式错误，模板列只允许数字，字母大小写，下划线，" +
                                "横杠，并且长度限制100：%s，字段:%s", fileName, field));
            }
        }

        // 验证数据库是否存在该模板,存在则直接返回模板ID
        String templateId = validTemplate(fileType, fileSeparator, Arrays.asList(fields));
        if(StringUtils.isNotEmpty(templateId)){
            return templateId;
        }

        // 上传模板文件
        String path = templateFilePath + Constants.SINGLE_SLASH + templateName;
        try {
            if (ExcelTypeEnum.XLS.getValue().equalsIgnoreCase(suffix) || ExcelTypeEnum.XLSX.getValue().equalsIgnoreCase(suffix)) {
                fileOperateCommonService.upload(getExcelTemplateInputStream(fields), path);
            }else{
                InputStream in = new ByteArrayInputStream(line.getBytes());
                fileOperateCommonService.upload(in, path);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        logger.info("上传模板文件成功:{}", templateName);

        // {"serial":1,"name":"name","type":"TEXT"}
        List<ColumnRuleDto> columnRuleList = new ArrayList<>();
        int i = 1;
        for (String field : fields) {
            ColumnRuleDto columnRuleDto = new ColumnRuleDto();
            columnRuleDto.setSerial(i);
            columnRuleDto.setName(field);
            columnRuleDto.setType(TEXT);
            columnRuleList.add(columnRuleDto);
            i++;
        }

        TemplateDTO templateDTO = new TemplateDTO();
        templateDTO.setColumnRule(JSONObject.toJSONString(columnRuleList));
        templateDTO.setTemplateName(templateName);
        templateDTO.setFileType(fileType);
        templateDTO.setFileSeparator(fileSeparator);
        return createTemplate(templateDTO);
    }

    private InputStream getExcelTemplateInputStream(String[] fields) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();

        List<ExcelExportEntity> entityList = new ArrayList<>();
        if(fields.length > 0){
            for (String field : fields) {
                entityList.add(new ExcelExportEntity(field));
            }
        }

        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null, null), entityList, list);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        workbook.write(baos);
        return new ByteArrayInputStream(baos.toByteArray());
    }

    private String validTemplate(int fileType, String fileSeparator, List<String> fieldList){
        List<ColumnRuleDto> columnRuleList = new ArrayList<>();
        for(String field : fieldList){
            ColumnRuleDto columnRuleDto = new ColumnRuleDto();
            columnRuleDto.setName(field);
            columnRuleDto.setType(TEXT);
            columnRuleList.add(columnRuleDto);
        }

        String md5 = encode(buildTemplateString(fileType, fileSeparator, columnRuleList));

        TemplateDTO templateDtoQuery = new TemplateDTO();
        templateDtoQuery.setMd5(md5);
        List<TemplateDTO> templateList = this.selectList(templateDtoQuery);
        if (CollectionUtils.isNotEmpty(templateList)) {
            return templateList.get(0).getId();
        }

        return null;
    }

    private String encode(String data) {
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        digest.update(data.getBytes());
        return encodeHex(digest.digest());
    }

    private String encodeHex(byte[] bytes) {
        StringBuilder buf = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            if ((b & 0xff) < 16) {
                buf.append("0");
            }
            buf.append(Long.toString(b & 0xff, 16));
        }
        return buf.toString().toUpperCase();
    }

    private String buildTemplateString(int fileType, String fileSeparator, List<ColumnRuleDto> columnRuleList){
        Collections.sort(columnRuleList);
        StringBuilder buf = new StringBuilder();
        buf.append(fileType).append(fileSeparator);
        if (CollectionUtils.isNotEmpty(columnRuleList)) {
            for(ColumnRuleDto columnRuleDto : columnRuleList){
                buf.append(columnRuleDto.getName()).append(columnRuleDto.getType());
            }
        }
        return buf.toString();
    }



    public boolean isValid(String regex, String name) {
        boolean flag = true;
        if(name.equals("\\t")){
            name = name.replace("\\t", "t");
        }

        if(name.contains("\"")){
            name = name.replace("\"", "");
        }

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(name);
        if(!matcher.matches()){
            flag = false;
        }
        return flag;
    }

    public String createTemplate(TemplateDTO templateDTO) throws Exception {
        if (StringUtils.isEmpty(templateDTO.getColumnRule())) {
            throw new BusinessException("columnRule不能为空");
        }
        if (StringUtils.isEmpty(templateDTO.getTemplateName())) {
            throw new BusinessException("templateName不能为空");
        }
        if (templateDTO.getFileType() == null) {
            throw new BusinessException("fileType不能为空");
        }
        if (StringUtils.isEmpty(templateDTO.getFileSeparator())) {
            throw new BusinessException("FileSeparator不能为空");
        }
        if (templateDTO.getFileSizeLimit() == null) {
            templateDTO.setFileSizeLimit(FILE_SIZE);
        }
        if (templateDTO.getEnableFormatLimit() == null) {
            templateDTO.setEnableFormatLimit(UNABLE);
        }
        if (templateDTO.getLengthLimit() == null) {
            templateDTO.setLengthLimit(FILE_NAME_LENGTH);
        }

        String id = ComUtil.getId();
        templateDTO.setId(id);

        List<ColumnRuleDto> columnRuleList = JSONUtils.toList(templateDTO.getColumnRule(), ColumnRuleDto.class);
        String md5 = encode(buildTemplateString(templateDTO.getFileType(), templateDTO.getFileSeparator(), columnRuleList));
        templateDTO.setMd5(md5);

        // 记录日志
        BdpLogUtil.log4Insert(templateDTO);

        this.insert(templateDTO);
        return id;
    }

    public void updateTemplate(TemplateDTO templateDTO) throws Exception {
        if (templateDTO.getId() == null) {
            throw new BusinessException("Id不能为空");
        }
        if (StringUtils.isEmpty(templateDTO.getColumnRule())) {
            throw new BusinessException("columnRule不能为空");
        }
        if (StringUtils.isEmpty(templateDTO.getTemplateName())) {
            throw new BusinessException("templateName不能为空");
        }
        if (templateDTO.getFileType() == null) {
            throw new BusinessException("fileType不能为空");
        }
        if (StringUtils.isEmpty(templateDTO.getFileSeparator())) {
            throw new BusinessException("FileSeparator不能为空");
        }
        if (templateDTO.getFileSizeLimit() == null) {
            templateDTO.setFileSizeLimit(FILE_SIZE);
        }
        if (templateDTO.getEnableFormatLimit() == null) {
            templateDTO.setEnableFormatLimit(UNABLE);
        }
        if (templateDTO.getLengthLimit() == null) {
            templateDTO.setLengthLimit(FILE_NAME_LENGTH);
        }

        TemplateDTO templateDTOQuery = this.selectByPrimaryKey(templateDTO.getId());
        if (templateDTOQuery == null) {
            throw new BusinessException(String.format("Id不存在%s", templateDTO.getId()));
        }

        // 已经关联文件的模板不能再进行修改
        CatalogTemplateDTO catalogTemplateDTO = CatalogTemplateDTO.builder().templateId(templateDTO.getId()).build();
        List<CatalogTemplateDTO> catalogTemplateDTOS = catalogTemplateService.selectList(catalogTemplateDTO);
        if (CollectionUtils.isNotEmpty(catalogTemplateDTOS)) {
            List<String> fileList =
                    catalogTemplateDTOS.stream().map(CatalogTemplateDTO::getFilePath).collect(Collectors.toList());
            throw new BusinessException(String.format("模板：{%s已关联文件列表{%s，不能再做修改操作！", templateDTO.getTemplateName(),
                    fileList.toString()));
        }

        // 只关联最新的模板文件，不删除原有模板文件
        logger.info("关联的最新模板文件为：{}", templateDTOQuery.getTemplateName());

        List<ColumnRuleDto> columnRuleList = JSONUtils.toList(templateDTO.getColumnRule(), ColumnRuleDto.class);
        String md5 = encode(buildTemplateString(templateDTO.getFileType(), templateDTO.getFileSeparator(), columnRuleList));
        templateDTO.setMd5(md5);

        // 记录日志
        BdpLogUtil.log4Update(templateDTO, templateDTOQuery);

        this.updateByPrimaryKeySelective(templateDTO);
    }

    public QueryRespBean<TemplateDTO> getTemplateList(Integer sort, String templateName, Integer pageNo,
                                                      Integer pageSize, boolean isFilter) {
        QueryRespBean<TemplateDTO> queryRespBean = new QueryRespBean<>();
        com.github.pagehelper.PageHelper.startPage(pageNo, pageSize);
        String orderField = ORDER_FIELD_LAST_UPDATE_DATE;
        String orderType = ORDER_TYPE_DESC;
        if (sort != null) {
            if (TIME_DESC == sort) {
                orderField = ORDER_FIELD_LAST_UPDATE_DATE;
                orderType = ORDER_TYPE_DESC;
            } else if (TIME_ASC == sort) {
                orderField = ORDER_FIELD_LAST_UPDATE_DATE;
                orderType = ORDER_TYPE_ASC;
            } else if (NAME_ASC == sort) {
                orderField = ORDER_FIELD_TEMPLATE_NAME;
                orderType = ORDER_TYPE_ASC;
            } else if (NAME_DESC == sort) {
                orderField = ORDER_FIELD_TEMPLATE_NAME;
                orderType = ORDER_TYPE_DESC;
            }
        }

        Page<TemplateDTO> templateList = templateDao.getTemplateList(templateName, orderField, orderType, isFilter);
        setTemplateIsRelatedFile(templateList);
        queryRespBean.setResult(templateList);
        BdpLogUtil.log4Query(queryRespBean);
        return queryRespBean;
    }

    /**
     * 模板添加是否关联文件标识
     * @param templateList
     */
    private void setTemplateIsRelatedFile(Page<TemplateDTO> templateList) {
        List<TemplateDTO> templateListResult = templateList.getResult();
        for (TemplateDTO templateDTO: templateListResult) {
            CatalogTemplateDTO catalogTemplateDTO = CatalogTemplateDTO.builder().templateId(templateDTO.getId()).build();
            List<CatalogTemplateDTO> catalogTemplateDTOS = catalogTemplateService.selectList(catalogTemplateDTO);
            if (CollectionUtils.isNotEmpty(catalogTemplateDTOS)) {
                templateDTO.setRelatedFile(true);
            }else {
                templateDTO.setRelatedFile(false);
            }

            // xls和xlsx统一表示成 xlsx
            if(templateDTO.getFileType() == FileType.EXCEL2003.getCode()){
                templateDTO.setFileType(FileType.EXCEL2007.getCode());
            }
        }
    }

    public void deleteTemplateByIds(TemplateDTO templateDTO) throws Exception {
        String idList = templateDTO.getId();
        logger.info("模板idList:{}", idList);
        String[] ids = idList.split(Constants.COMMA);
        for (String id : ids) {
            // 判断模板是否关联目录，关联目录不能删除
            checkTempIsUsedByCataLog(id);

            // 删除对应模板文件
            TemplateDTO templateDTOQuery = this.selectByPrimaryKey(id);
            if (templateDTOQuery == null) {
                throw new BusinessException(String.format("根据id未查找到关联的模板：%s", id));
            }

            String templateName = templateDTOQuery.getTemplateName();
            // 判断文件是否存在
            boolean isExist = fileOperateCommonService.exists(templateFilePath + Constants.SINGLE_SLASH + templateName);
            if (isExist) {
                boolean isDeleted = fileOperateCommonService.delete(templateFilePath + Constants.SINGLE_SLASH + templateName, false);
                if (!isDeleted) {
                    logger.error("删除文件失败：{}", templateName);
                    continue;
                }
            }

            // 记录日志
            BdpLogUtil.log4Delete(templateDTOQuery);

            // 删除数据库模板记录
            this.deleteByPrimaryKey(id);
        }
    }

    private void checkTempIsUsedByCataLog(String id) {
        CatalogTemplateDTO catalogTemplateDTO = new CatalogTemplateDTO();
        catalogTemplateDTO.setTemplateId(id);
        List<CatalogTemplateDTO> catalogTemplateDTOQueryList = catalogTemplateService.selectList(catalogTemplateDTO);
        if (CollectionUtils.isNotEmpty(catalogTemplateDTOQueryList)) {
            List<String> filePathList =
                    catalogTemplateDTOQueryList.stream().map(CatalogTemplateDTO::getFilePath).collect(Collectors.toList());
            throw new BusinessException(String.format("模板已关联文件，不能删除：{%s", filePathList.toString()));
        }
    }

    public void downloadTemplate(String templateId, HttpServletResponse response) throws Exception {
        TemplateDTO templateDTOQuery = this.selectByPrimaryKey(templateId);
        if (templateDTOQuery == null) {
            throw new BusinessException(String.format("没有查到对应id的模板文件：%s", templateId));
        }
        fileOperateCommonService.downloadFile(templateFilePath + Constants.SINGLE_SLASH + templateDTOQuery.getTemplateName(), response);
    }

    public List<TemplateDTO> getTemplateListByName(String templateName) {
        return templateDao.getTemplateListByName(templateName);
    }

    public List<ColumnInfo> getTemplateColumnList(String catalogPath) throws Exception {
        CatalogTemplateDTO catalogTemplateDTOQuery = new CatalogTemplateDTO();
        catalogTemplateDTOQuery.setCatalogPath(catalogPath);
        CatalogTemplateDTO catalogTemplateDTO = catalogTemplateService.selectOne(catalogTemplateDTOQuery);
        if (catalogTemplateDTO == null) {
            throw new BusinessException(String.format("catalogPath：%s的目录没有关联模板", catalogPath));
        }

        TemplateDTO templateDTO = this.selectByPrimaryKey(catalogTemplateDTO.getTemplateId());
        if (templateDTO == null) {
            throw new BusinessException(String.format("没有查到数据，请确保templateId：%s的模板是否存在",
                    catalogTemplateDTO.getTemplateId()));
        }
        if (StringUtils.isEmpty(templateDTO.getColumnRule())) {
            throw new BusinessException(String.format("templateId：%s对应的模板没有列规则数据",
                    catalogTemplateDTO.getTemplateId()));
        }
        return JSONUtils.toList(templateDTO.getColumnRule(), ColumnInfo.class);
    }

    public List<ColumnInfo> getTemplateColumnListById(String templateId) throws Exception {
        TemplateDTO templateDTO = this.selectByPrimaryKey(templateId);
        if (templateDTO == null) {
            throw new BusinessException(String.format("没有查到数据，请确保templateId：%s的模板是否存在", templateId));
        }
        if (StringUtils.isEmpty(templateDTO.getColumnRule())) {
            throw new BusinessException(String.format("templateId：%s对应的模板没有列规则数据", templateId));
        }
        return JSONUtils.toList(templateDTO.getColumnRule(), ColumnInfo.class);
    }

    private String checkParams(TemplateDTO templateDTO) {
        MultipartFile file = templateDTO.getFile();
        String separator = templateDTO.getFileSeparator();
        // 校验分隔符
        if (separator == null || "".equals(separator)) {
            throw new BusinessException("模板分隔符不能为空！");
        }
        String filename = file.getOriginalFilename();
        String[] split = filename.split("\\.");
        String suffix = split[split.length - 1];
        String[] types = templateType.split("\\|");
        List<String> typeList = Arrays.asList(types);
        if (!typeList.contains(suffix)) {
            throw new BusinessException("上传模板文件类型仅支持:" + templateType);
        }

        // 校验分隔符
        if (!isValid(TEMPLATE_SEPARATOR_PATTERN, separator)) {
            throw new BusinessException(String.format("上传模板文件分隔符请匹配%s正则表达式", TEMPLATE_SEPARATOR_PATTERN));
        }

        return suffix;
    }

    public List<TemplateDTO> getTemplateListByCatalogPath(String catalogPath) {
        return templateDao.getTemplateListByCatalogPath(catalogPath);
    }

    public List<TemplateDTO> getTemplateDTOAndFilePathByCatalogPath(String catalogPath) {

        return templateDao.getTemplateDTOAndFilePathByCatalogPath(catalogPath);
    }

    public Boolean deleteTempTemplate(TemplateDTO templateDTO) throws IOException {
        String templateName = templateDTO.getTemplateName();
        CheckParaUtils.checkStringValidity(templateName, logger, "模板名称不能为空！");
        logger.info("删除临时模板文件：{}", templateFilePath + Constants.SINGLE_SLASH + templateName);
        String filePath = templateFilePath + Constants.SINGLE_SLASH + templateName;
        if (!fileOperateCommonService.exists(filePath)) {
            return true;
        }

        return fileOperateCommonService.delete(filePath, false);
    }
}
